package com.ljy.my_study.java.gc.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/**
 * @author lijunying
 * @date 2021/1/6 14:18
 */
public class SoftRefQ {

    public static class User{
        public User(int id,String name){
            this.id=id;
            this.name=name;
        }

        public int id;
        public String name;

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    static ReferenceQueue<User> softQueue=null;

    public static class CheckRefQueue extends Thread{

        @Override
        public void run() {
            while(true){
                if(softQueue!=null){
                    UserSoftReference obj=null;
                    try{
                        obj= (UserSoftReference) softQueue.remove();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(obj!=null){
                        System.out.println("user id "+obj.uid+" delete.");
                    }
                }
            }
        }
    }

    public static class UserSoftReference extends SoftReference<User> {

        public int uid;

        public UserSoftReference(User referent, ReferenceQueue<? super User> q) {
            super(referent, q);
            uid=referent.id;
        }
    }

    /**
     * -Xmx10m
     * ReferenceQueue是队列，进行gc时可以获取被删除的对象
     * @param args
     */
    public static void main(String[] args) {
        Thread t=new CheckRefQueue();
//        t.setDaemon(true);
        t.start();

        softQueue=new ReferenceQueue<>();
        User u=new User(1,"James");
        UserSoftReference userSoftReference=new UserSoftReference(u,softQueue);
        u=null;
        System.out.println(userSoftReference.get());
        System.gc();
        System.out.println("after gc");
        System.out.println(userSoftReference.get());
        byte[] b=new byte[1024*925*7];
        System.out.println(userSoftReference.get());
    }
}
